package com.reebake.ideal.desensitize.serializer;

import cn.hutool.core.lang.Assert;
import cn.hutool.extra.spring.SpringUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.reebake.ideal.desensitize.annotation.JsonDesensitize;
import com.reebake.ideal.desensitize.enums.DesensitizeType;
import com.reebake.ideal.desensitize.core.DesensitizeHandler;

import java.io.IOException;

public class DesensitizeSerializer extends JsonSerializer<String> implements ContextualSerializer {
    private String ruleName;

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        DesensitizeHandler desensitizeHandler = SpringUtil.getBean(DesensitizeHandler.class);
        String desensitizeValue = desensitizeHandler.desensitize(value, ruleName);
        gen.writeString(desensitizeValue);
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        if (property != null) {
            JsonDesensitize annotation = property.getAnnotation(JsonDesensitize.class);
            if (annotation != null) {
                Assert.notNull(annotation.type());
                this.ruleName = annotation.type().name();
                if (annotation.type() == DesensitizeType.CUSTOMIZE) {
                    Assert.notBlank(annotation.value());
                    this.ruleName = annotation.value();
                }
            }
        }
        return this;
    }
}
